package org.appfuse.webapp.action;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.appfuse.Constants;
import org.appfuse.model.BasicInfo;
import org.appfuse.model.User;
import org.appfuse.model.Zb910;
import org.appfuse.service.BasicInfoManager;
import org.appfuse.service.UserManager;
import org.appfuse.service.ZnodeTreeManager;
import org.appfuse.webapp.form.BasicInfoForm;

/**
 * Action class to handle CRUD on a Menu object
 * 
 * @struts.action name="criteriaForm" path="/criterias" scope="request"
 *                validate="false" parameter="method" input="mainMenu"
 * @struts.action name="criteriaForm" path="/editMenu" scope="request"
 *                validate="false" parameter="method" input="list"
 * @struts.action name="criteriaForm" path="/saveMenu" scope="request"
 *                validate="true" parameter="method" input="edit"
 * @struts.action-set-property property="cancellable" value="true"
 * @struts.action-forward name="edit" path="/WEB-INF/pages/criteriaForm.jsp"
 * @struts.action-forward name="list" path="/WEB-INF/pages/criteriaList.jsp"
 * @struts.action-forward name="search" path="/criterias.html" redirect="true"
 */
public final class BasicInfoAction extends BaseAction {

	public ActionForward cancel(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("edit");
	}

	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'delete' method");
		}

		return mapping.findForward("edit");
	}

	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'edit' method");
		}

		BasicInfoForm basicInfoForm = (BasicInfoForm) form;
		UserManager userMgr = (UserManager) getBean("userManager");
		String currentUserName = request.getRemoteUser();
		User currentUser = userMgr.getUserByUsername(currentUserName);

		BasicInfoManager basicInfoMgr = (BasicInfoManager) getBean("basicInfoManager");
		String recordId = currentUser.getRecordId();
		
		/*
		 * 1. if recordid is null then constructs a basicinfo, gets it's id and updates current user's recordid.
		 */
		BasicInfo basicInfo = null;
		if (StringUtils.isEmpty(recordId)){
			basicInfo = new BasicInfo();
			basicInfoMgr.save(basicInfo);
			basicInfoForm.setId(basicInfo.getId());
			currentUser.setRecordId(basicInfo.getId());
			userMgr.saveUser(currentUser);
		}else{
			basicInfo = basicInfoMgr.findById(recordId);
			basicInfoForm = (BasicInfoForm) convert(basicInfo);
			Set set = basicInfo.getZb910s();
			String zb910 = "";
			Iterator it = set.iterator();
			while (it.hasNext()){
				Zb910 zb910Tmp = (Zb910) it.next();
				if (zb910Tmp != null){
					zb910 = zb910Tmp.getId().getDmcod();
					break;
				}
			}
			
			basicInfoForm.setZb910(zb910);
			updateFormBean(mapping, request, basicInfoForm);
		}
		
		return mapping.findForward("edit");
	}

	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'save' method!");
		}
		ActionMessages errors = form.validate(mapping, request);

		if (!errors.isEmpty()) {
			saveErrors(request, errors);
			return mapping.findForward("add");
		}

		// Extract attributes and parameters we will need
		ActionMessages messages = new ActionMessages();
		BasicInfoForm basicInfoForm = (BasicInfoForm) form;

		BasicInfoManager mgr = (BasicInfoManager) getBean("basicInfoManager");
		BasicInfo basicInfo = (BasicInfo) convert(basicInfoForm);
		basicInfo.getBj77s().addAll(Constants.BJ77_MAP.values());
		String zb910 = basicInfoForm.getZb910();
		basicInfo.getZb910s().add(Constants.ZB910_MAP.get(basicInfoForm.getZb910()));
		ZnodeTreeManager nodeMgr = (ZnodeTreeManager) getBean(Constants.ZNODETREE_MANAGER);
		List nodes = nodeMgr.findAll();
		basicInfo.getNodes().addAll(nodes);
		//UserManager userMgr = (UserManager) getBean("userManager");
		//String userName = (String) request.getRemoteUser();
		//User currentUser = (User) userMgr.getUserByUsername(userName);
		//basicInfo.setUserId(currentUser.getId().toString());

		try {
			mgr.update(basicInfo);

		} catch (Exception e) {
			throw e;
		}

		// add success messages
		messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
				"basicInfo.saved"));
		// save messages in session to survive a redirect
		saveMessages(request.getSession(), messages);

		return mapping.findForward("edit");
	}

	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'save' method");
		}

		return mapping.findForward("edit");
	}

	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'list' method");
		}

		return mapping.findForward("list");
	}

}
